package com.csii.result;

import com.baomidou.mybatisplus.annotation.TableName;
import com.csii.adhoc.annotation.Excel;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description: table打印
 * @author: panChuanJiang
 * @create: 2021-07-13 11:11
 */
@Slf4j
public class TableHtmlBuilder {

    public static String buildTableHtml(List<?> data) {
        if (data == null || data.size() == 0) {
            return null;
        }
        Class tClass = data.get(0).getClass();
        TableName tableNameAno = (TableName) tClass.getAnnotation(TableName.class);
        String tableName = tableNameAno == null ? "defaultTable" : tableNameAno.value();
        StringBuilder sb = new StringBuilder();
        sb.append("<form id=\"").append(tableName).append("\">")
                .append("<table class=\"table-condensed table-bordered table\">")
                .append("<tr>");
        Field[] fields = tClass.getDeclaredFields();
        List<Field> fieldList = Arrays.stream(fields).filter(x -> x.getAnnotation(Excel.class) != null)
                .collect(Collectors.toList());
        if (fieldList.size() == 0) {
            log.error("{},没有@Excel注解修饰的属性", tClass.getName());
            return "";
        }
        fieldList.forEach(x -> x.setAccessible(true));
        fieldList.forEach(x -> sb.append("<td>").append(x.getAnnotation(Excel.class).name()).append("</td>"));
        sb.append("</tr>");
        //构建数据
        data.forEach(x -> {
            sb.append("<tr>");
            fieldList.forEach(y -> {
                try {
                    sb.append("<td>");
                    if (y.getType().equals(Date.class)) {
                        String format = "yyyy-MM-dd";
                        JsonFormat formatAno = y.getAnnotation(JsonFormat.class);
                        if (formatAno != null) {
                            String pattern = formatAno.pattern();
                            format = StringUtils.isEmpty(pattern) ? format : pattern;
                        }
                        SimpleDateFormat sdf = new SimpleDateFormat(format);
                        sb.append(sdf.format(y.get(x)));
                    } else {
                        sb.append(y.get(x));
                    }
                    sb.append("</td>");
                } catch (IllegalAccessException e) {
                    log.error("反射异常，", e);
                }
            });
            sb.append("</tr>");
        });
        sb.append("</table>");
        sb.append("</form>");
        return sb.toString();
    }
}
